using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using Impact.Web.Foundation;
using Impact.Controllers;
using Impact.Infrastructure.Exceptions;
using Impact.Views;
using Impact.Model.Objects;

namespace Impact.Web.Controls
{
    public partial class DisplaySearchResults : Impact.Web.Foundation.DynamicPageControlBase, Impact.Views.IContentControl
    {
        /// <summary>
        /// loads the search results into the repeater
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Check.Require(results, "Results are required");
            resultsRepeater.DataSource = results;
            resultsRepeater.DataBind();
        }

        /// <summary>
        /// Retrieves the title for the page this control is building
        /// </summary>
        protected override string PageTitle
        {
            get { return "Search Results"; }
        }

        /// <summary>
        /// Gets or Sets the SearchResults that will be displayed on this control
        /// </summary>
        public List<SearchResult> SearchResults
        {
            get { return results; }
            set { results = value; }
        }
        private List<SearchResult> results;

        /// <summary>
        /// given a description field, strips the HTML and highlights the terms used on the search
        /// </summary>
        /// <param name="description"></param>
        /// <returns></returns>
        protected string FormatDescription(string description)
        {
            string terms = Request.QueryString["terms"];
            if (!string.IsNullOrEmpty(terms) && !string.IsNullOrEmpty(description))
            {
                // strip HTML from the description
                description = Regex.Replace(description, @"<(.|\n)*?>", string.Empty);
                description = Regex.Replace(description, terms,
                    string.Format("<span class=\"highlight\">{0}</span>", terms), RegexOptions.IgnoreCase);
            }
            return description;
        }

        #region IContentControl Members

        /// <summary>
        /// sets the search results that will be used as a data source for this control
        /// </summary>
        public object DataSource
        {
            set { results = (List<SearchResult>)value; }
        }

        /// <summary>
        /// called to perform initialization before the control loads
        /// </summary>
        public void PreInit()
        {
        }

        #endregion
    }
}